package com.hmall.gateway.filters;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    private final AntPathMatcher antPathMatcher=new AntPathMatcher();

    public int getOrder() {
        return 0; // Set the order of this filter
    }

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取请求头
        ServerHttpRequest request = exchange.getRequest();
        //放行不需要认证的请求
        if(isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }
        //获取请求头中的token
        String token = null;
        List<String> authorization = request.getHeaders().get("authorization");
        if (authorization != null && !authorization.isEmpty()) {
            token = authorization.get(0);
        }
        //验证token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        }catch(Exception e){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //将用户id放入请求头中
        String userIdStr = String.valueOf(userId);
        ServerWebExchange swe = exchange.mutate().request(build -> build.header("user-Info", userIdStr)).build();

        return chain.filter(swe);
    }


    public boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }
}
